package com.zlsy.secondtime.threadcoreknowledge.stopthreads;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhouliang
 * @date 2020/5/15 9:55
 * 最佳实践2：在catch子语句中调用 Thread.currentThread().interrupt();设置中断状态，
 * 以便于在后续的执行中，依然能够检查到刚才发生了中断。
 */
@Slf4j
public class RightWayStopThreadInProd2 implements Runnable {

    @Override
    public void run() {
        while (true) {
            if (!Thread.currentThread().isInterrupted()){
                reInterrupted();
            }else {
                log.error("线程被中断啦！");
                break;
            }
        }
    }

    private void reInterrupted() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        RightWayStopThreadInProd2 r = new RightWayStopThreadInProd2();
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
}